﻿using HpxWMS_Api.CustomExcption;
using HpxWMS_Api.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Filters;

namespace HpxWMS_Api.CustomAttribute
{
    public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            var exception = actionExecutedContext.Exception;
            if (exception is ClientException)
            {
                switch ((exception as ClientException).StatusCode)
                {
                    case HttpStatusCode.BadRequest:
                        {
                            // 返回结果
                            var result = new R<string>() { Code = "900", Message = "请求参数错误" };
                            actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, result);
                        }
                        break;
                    default:
                        {
                            // 返回结果
                            var result = new R<string>() { Code = "999", Message = "内部服务器错误,请联系管理员" };
                            actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, result);
                        }
                        break;
                }

            }
            else if (exception is BusinessException)
            {
                var businessException = (BusinessException)exception;
                // 返回结果
                var result = new R<string>() { Code = businessException.Code, Message = businessException.Message };
                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.OK, result);
            }
            else
            {
                // 返回结果
                var result = new R<string>() { Code = "999", Message = "内部服务器错误,请联系管理员" };
                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, result);
            }
        }
    }
}